const FAVORITES = 'favorites';
const ERRORS = 'errors';
const COUNTER = 'counter';

function formatDate(date) {
    let d = new Date(date),
        month = '' + (d.getMonth() + 1),
        day = '' + d.getDate(),
        year = d.getFullYear();

    if (month.length < 2)
        month = '0' + month;
    if (day.length < 2)
        day = '0' + day;

    return [year, month, day].join('-');
}

export function getErrors() {
    const errors = localStorage.getItem(ERRORS);
    return errors ? JSON.parse(errors) : {};
}

export function getTodayErrors() {
    const errors = getErrors();
    const today = formatDate(new Date());
    if (!errors[today]) {
        errors[today] = {};
    }

    return [errors[today], errors];
}

export function getErrorsInRange(range) {
    if (range === 1) {
        return getTodayErrors();
    }

    const errors = getErrors();
    return [Object.keys(errors)
        .sort()
        .reverse()
        .slice(0, range)
        .reduceRight((acc, cur) => {
            return {...acc, ...(errors[cur])}
            }, {})];
}

export function addError(pinyin) {
    const [todayErrors, errors] = getTodayErrors();
    if (todayErrors[pinyin]) {
        todayErrors[pinyin] += 1;
    } else {
        todayErrors[pinyin] = 1;
    }

    localStorage.setItem(ERRORS, JSON.stringify(errors));
}

export function getFavorites() {
    const favorites = localStorage.getItem(FAVORITES);
    return favorites ? JSON.parse(favorites) : [];
}

export function toggleFavorite(favoriteItem) {
    const favorites = getFavorites();
    if (!favorites.includes(favoriteItem)) {
        favorites.push(favoriteItem);
    } else {
        favorites.splice(favorites.indexOf(favoriteItem), 1);
    }
    localStorage.setItem(FAVORITES, JSON.stringify(favorites));

    return true;
}

export function getCounter() {
    const counter = localStorage.getItem(COUNTER);
    return counter ? JSON.parse(counter) : {
        trained: 0,
        stronger: 0,
    };
}

export function saveCounter(counter) {
    localStorage.setItem(COUNTER, JSON.stringify(counter));
    return true;
}
